<template>
  <div>
    <table class="table report-table">
      <colgroup>
        <col width="10%" />
        <col width="30%" />
        <col width="15%" />
        <col width="15%" />
        <col width="15%" />
        <col width="15%" />
      </colgroup>
      <tbody>
        <tr>
          <td colspan="6" style="border: none">
            <h3 class="report-title">贵州省融资担保机构收益情况表</h3>
          </td>
        </tr>
        <tr rowspan="4">
          <td colspan="6" style="border: none" class="text-left">
            <div>表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：DBG03</div>
            <div>制表机关：贵州省人民政府金融工作办公室</div>
            <div class="d-flex justify-content-between">
              <div>填报单位：</div>
              <div>单位：万元</div>
            </div>
          </td>
        </tr>
        <tr>
          <td rowspan="3">序号</td>
          <td rowspan="3">项目</td>
          <td>A</td>
          <td>B</td>
          <td>C</td>
          <td>D</td>
        </tr>
        <tr>
          <td rowspan="2">年初数(万元)</td>
          <td colspan="3">本年度累计数（发生额 万元）</td>
        </tr>
        <tr>
          <td>公司制</td>
          <td>非公司制</td>
          <td>合计</td>
        </tr>
        <tr v-for="(p, index) of reportDetail" :key="index">
          <td>{{ p.order_num }}</td>
          <td
            class="text-left"
            v-if="[2, 4, 5, 6].includes(+p.order_num)"
            :class="[2, 4].includes(+p.order_num) ? 'text-indent' : 'item-list'"
          >
            {{ tableColumn[p.order_num] }}
          </td>
          <td class="text-left" v-else>{{ tableColumn[p.order_num] }}</td>
          <td :class="tdClass">
            <span v-if="isViewMode">{{ p.year_begin_funds }}</span>
            <el-input
              v-else
              v-model="p.year_begin_funds"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="年初数"
            ></el-input>
          </td>
          <td :class="tdClass">
            <span v-if="isViewMode">{{ p.com_funds }}</span>
            <el-input
              v-else
              v-model="p.com_funds"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="公司制"
            ></el-input>
          </td>
          <td :class="tdClass">
            <span v-if="isViewMode">{{ p.un_com_funds }}</span>
            <el-input
              v-else
              v-model="p.un_com_funds"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="非公司制"
            ></el-input>
          </td>
          <td>{{ add(p.com_funds, p.un_com_funds) || '0.00' }}</td>
        </tr>

        <tr rowspan="4">
          <td colspan="6" style="border: none">
            <div class="d-flex justify-content-between">
              <div>单位负责人：</div>
              <div>统计负责人：</div>
              <div>填表人：</div>
              <div>
                填报日期：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              </div>
            </div>
            <div class="d-flex">
              <div>填报说明：</div>
              <div class="flex-1 text-left">
                <div>1．本表由融资性担保机构填报(年检不合格的辖内融资担保机构不参加数据报送)。</div>
                <div>
                  2．本表统计范围:本省（区、市）登记注册的融资担保法人机构及合伙制企业为统计对象全部汇总填报（本省（区、市）融资担保法人机构在省（区、市）外设立的分支机构的有关情况需汇总至法人机构统一填报。
                </div>
                <div>3．本报表为季报，报送时间为季后15日前。</div>
                <div>4.填列的金额保留两位小数。</div>
              </div>
            </div>
            <div></div>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="text-center pt-2" v-if="!isViewMode">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        保存
      </el-button>
      <el-button class="btn-long" @click="onClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { add } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
const tableColumn = {
  1: '1.担保业务收入',
  2: '其中：1.1融资性担保费收入',
  3: '2.担保业务成本',
  4: '其中：2.1融资性担保赔偿支出 ',
  5: '2.2融资性分担保费支出',
  6: '2.3营业税金及附加',
  7: '3.担保业务利润',
  8: '4.利息净收入（净支出则前加“－”号填列）',
  9: '5.其他业务利润',
  10: '6.业务及管理费',
  11: '7.投资收益（投资损失则前加“－”号填列）',
  12: '8.营业利润',
  13: '9.营业外净收入（净亏损则前加“－”号填列）',
  14: '10.资产减值损失（转回的金额则前加“－”号填列）',
  15: '11.所得税',
  16: '12.净利润（净亏损则前加“－”号填列）',
}
export default {
  components: {},
  props: {
    editMode: { type: Boolean, default: false },
  },
  data() {
    return {
      tableColumn,
      tableName: 'report_month',
      params: {
        index: 1,
        size: 1,
        'report_type.eq': 3,
        subKey: 'report_month_income_detail.report_month_id',
      },
      order: {
        create_time: 'desc',
      },
      loading: false,
      reportMonth: {},
      reportDetail: [],
      submitLoading: false,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user']),
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
    isViewMode() {
      if (this.editMode) {
        return false
      }
      return true
    },
  },
  watch: {},
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    add,
    initData() {
      this.reportDetail = []
      Object.keys(this.tableColumn).forEach(key => {
        this.reportDetail.push({
          order_num: key,
        })
      })
    },
    submit() {
      const date = new Date()
      if (
        date.getFullYear() === +this.reportMonth.year_number &&
        date.getMonth() === +this.reportMonth.month_number
      ) {
        this.updateData()
      } else {
        this.postData()
      }
    },
    updateData() {
      this.submitLoading = true
      const masterData = {
        report_month_id: this.reportMonth.report_month_id,
        service_id: this.clientId,
        submit_person_name: this.user.realName,
      }
      const slaveData = []
      this.reportDetail.forEach(item => {
        slaveData.push({
          id: item.id,
          report_month_id: item.report_month_id,
          year_begin_funds: item.year_begin_funds,
          com_funds: item.com_funds,
          un_com_funds: item.un_com_funds,
        })
      })
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: 'report_month',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'report_month_income_detail',
      }
      this.$api
        .relatedUpdate(this.$serviceName, formData)
        .then(() => {
          this.$message.success('保存成功')
          this.$emit('success', true)
          this.onClose()
        })
        .catch(() => {
          this.$message.error('保存失败，请重试！！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    postData() {
      this.submitLoading = true
      const masterData = {
        month_number: new Date().getMonth(),
        year_number: new Date().getFullYear(),
        service_id: this.clientId,
        submit_person_name: this.user.realName,
        report_no: this.reportMonth.report_no,
        report_type: 3,
      }
      const slaveData = []
      this.reportDetail.forEach(item => {
        slaveData.push({
          order_num: item.order_num,
          year_begin_funds: item.year_begin_funds,
          com_funds: item.com_funds,
          un_com_funds: item.un_com_funds,
        })
      })
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: 'report_month',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'report_month_income_detail',
      }
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(() => {
          this.$message.success('保存成功')
          this.$emit('success', true)
          this.onClose()
        })
        .catch(() => {
          this.$message.error('保存失败，请重试！！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    onClose() {
      this.$emit('close', true)
    },
    getData(params) {
      this.initData()
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, { ...this.params, ...params }, this.order)
        .then(res => {
          const data = (res && res.data) || {}
          this.reportMonth = (data.data && data.data[0]) || {}
          const detail = this.reportMonth.report_month_income_detail || []
          const date = new Date()
          if (
            date.getFullYear() === +this.reportMonth.year_number &&
            date.getMonth() === +this.reportMonth.month_number
          ) {
            this.$emit('back', false)
          }
          if (detail.length) {
            this.reportDetail = detail.sort((a, b) => a.order_num - b.order_num)
          }
          this.getFee()
        })
        .finally(() => {
          this.loading = false
        })
    },
    getFee() {
      const date = new Date()
      if (
        date.getFullYear() === +this.reportMonth.year_number &&
        date.getMonth() === +this.reportMonth.month_number
      ) {
        return
      }
      const params = {
        isBIQuery: 1,
        'service_id.eq': this.clientId,
      }
      params['current_month.eq'] = `${new Date().getFullYear()}${new Date().getMonth()}`
      this.$api.getData(this.$serviceName, 'pro_warranty_fee_view', params).then(res => {
        const data = (res && res.data && res.data[0]) || {}
        const item = this.reportDetail[1]
        item.com_funds = data.warranty_fee
        this.reportDetail.splice(1, 1, item)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
$report-td-border-color: #000;
.report-table {
  position: relative;
  tbody td {
    border: 1px solid $report-td-border-color;
    vertical-align: middle;
    text-align: center;
  }
}
.report-title {
  font-size: 1.5rem;
  font-family: '方正小标宋简体', 'SimSun', cursive;
  margin: 0;
  text-align: center;
}
.text-indent {
  text-indent: 2rem;
}
.item-list {
  padding-left: 5.7rem;
}
</style>
